<script setup>
    import { ref, onMounted } from 'vue'
    import { ElMessage, ElMessageBox } from 'element-plus'
    import { Document, Delete, Plus } from '@element-plus/icons-vue'

    // 使用策略模式管理角色和权限
    const roleStrategy = {
        admin: {
            name: '管理员',
            permissions: ['user:manage', 'role:manage', 'permission:manage']
        },
        editor: {
            name: '编辑者',
            permissions: ['content:create', 'content:edit']
        },
        visitor: {
            name: '访客',
            permissions: ['content:view']
        }
    }

    // 当前显示的页面（根据URL参数决定）
    const currentPage = ref('userManagement')

    // 强制重新加载页面（确保跳转生效）
    const reloadForRedirect = () => {
        window.location.reload()
    }

    // 切换页面的函数（保留您原来的方式）
    const switchPage = (pageName) => {
        window.location.href = window.location.pathname + `?page=${pageName}`
    }

    // 初始化时检查URL参数
    onMounted(() => {
        const urlParams = new URLSearchParams(window.location.search)
        currentPage.value = urlParams.get('page') || 'userManagement'
    })

    // 用户数据
    const users = ref([
        { id: 1, username: 'admin', password: '123456', role: 'admin', createTime: '2023-01-01' },
        { id: 2, username: 'editor1', password: '123456', role: 'editor', createTime: '2023-01-02' },
        { id: 3, username: 'visitor1', password: '123456', role: 'visitor', createTime: '2023-01-03' },
        { id: 4, username: 'admin2', password: '123456', role: 'admin', createTime: '2023-01-04' },
        { id: 5, username: 'editor2', password: '123456', role: 'editor', createTime: '2023-01-05' },
        { id: 6, username: 'visitor2', password: '123456', role: 'visitor', createTime: '2023-01-06' },
        { id: 7, username: 'admin3', password: '123456', role: 'admin', createTime: '2023-01-07' },
        { id: 8, username: 'editor3', password: '123456', role: 'editor', createTime: '2023-01-08' },
        { id: 9, username: 'visitor3', password: '123456', role: 'visitor', createTime: '2023-01-09' },
        { id: 10, username: 'admin4', password: '123456', role: 'admin', createTime: '2023-01-10' },
        { id: 11, username: 'editor4', password: '123456', role: 'editor', createTime: '2023-01-11' },
        { id: 12, username: 'visitor4', password: '123456', role: 'visitor', createTime: '2023-01-12' }
    ])

    // 表单数据
    const userForm = ref({
        username: '',
        password: '',
        role: ''
    })

    // 对话框控制
    const showUserDialog = ref(false)
    const selectedUser = ref(null)

    // 分页控制（保留您原来的分页方式）
    const userPageNum = ref(1)
    const userTotal = ref(users.value.length)
    const userPageSize = ref(5)

    // 表单验证规则
    const rules = {
        username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 20, message: '长度在3到20个字符', trigger: 'blur' }
        ],
        password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 20, message: '长度在6到20个字符', trigger: 'blur' }
        ]
    }

    // 获取分页数据
    const getPaginatedUsers = () => {
        const start = (userPageNum.value - 1) * userPageSize.value
        const end = start + userPageSize.value
        return users.value.slice(start, end)
    }

    // 用户操作
    const createUser = () => {
        const newUser = {
            id: users.value.length + 1,
            ...userForm.value,
            createTime: new Date().toISOString().split('T')[0]
        }
        users.value.unshift(newUser)
        userTotal.value = users.value.length
        showUserDialog.value = false
        ElMessage.success('用户创建成功')
    }

    const deleteUser = (id) => {
        ElMessageBox.confirm('确定删除此用户?', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            users.value = users.value.filter(user => user.id !== id)
            userTotal.value = users.value.length
            ElMessage.success('删除成功')
        })
    }

    const viewUserDetails = (user) => {
        selectedUser.value = user
    }

    // 分页变化处理（保留您原来的分页处理方式）
    const onUserSizeChange = (size) => {
        userPageSize.value = size
    }

    const onUserCurrentChange = (num) => {
        userPageNum.value = num
    }
</script>

<template>
    <div class="page-container">
        <!-- 顶部导航（保留您原来的跳转方式） -->
        <el-card>
            <template #header>
                <div class="header" style="display: flex; align-items: center; justify-content: space-between;">
                    <div style="display: flex; align-items: center;">
                        <span style="margin-right: 20px; font-size: 18px; font-weight: bold;">用户管理</span>
                        <el-button type="primary" @click="switchPage('campusCardManagement')"
                            style="margin-right: 10px;" plain>
                            校园卡管理
                        </el-button>
                        <el-button type="primary" @click="switchPage('vendingMachine')" style="margin-right: 10px;"
                            plain>
                            自动售货机
                        </el-button>
                    </div>
                    <div class="extra" style="display: flex; align-items: center;">
                        <el-button type="primary" @click="showUserDialog = true" :icon="Plus">
                            新建用户
                        </el-button>
                    </div>
                </div>
            </template>

            <!-- 用户管理内容 -->
            <div v-if="currentPage === 'userManagement'">
                <!-- 用户表格 -->
                <el-table :data="getPaginatedUsers()" style="width: 100%">
                    <el-table-column prop="id" label="ID" width="80" />
                    <el-table-column prop="username" label="用户名" />
                    <el-table-column label="角色">
                        <template #default="{ row }">
                            {{ roleStrategy[row.role]?.name || row.role }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建时间" />
                    <el-table-column label="操作" width="180">
                        <template #default="{ row }">
                            <el-button size="small" :icon="Document" @click="viewUserDetails(row)">详情</el-button>
                            <el-button size="small" :icon="Delete" type="danger"
                                @click="deleteUser(row.id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页条（保留您原来的分页组件） -->
                <el-pagination v-model:current-page="userPageNum" v-model:page-size="userPageSize"
                    :page-sizes="[5, 10, 15]" :total="userTotal" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="onUserSizeChange" @current-change="onUserCurrentChange"
                    style="margin-top: 20px; justify-content: flex-end;" />
            </div>

            <!-- 其他页面内容 -->
            <div v-else>
                <el-empty :description="`${currentPage === 'campusCardManagement' ? '校园卡' : '自动售货机'}功能开发中`" />
            </div>
        </el-card>

        <!-- 新建用户对话框 -->
        <el-dialog v-model="showUserDialog" title="新建用户" width="500px">
            <el-form :model="userForm" :rules="rules" label-width="80px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="userForm.username" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="userForm.password" type="password" />
                </el-form-item>
                <el-form-item label="角色">
                    <el-select v-model="userForm.role" placeholder="请选择角色">
                        <el-option v-for="(role, key) in roleStrategy" :key="key" :label="role.name" :value="key" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="showUserDialog = false">取消</el-button>
                <el-button type="primary" @click="createUser">确定</el-button>
            </template>
        </el-dialog>

        <!-- 用户详情对话框 -->
        <el-dialog v-model="selectedUser" :title="`用户详情 - ${selectedUser?.username}`" width="600px">
            <el-descriptions :column="2" border>
                <el-descriptions-item label="用户名">{{ selectedUser?.username }}</el-descriptions-item>
                <el-descriptions-item label="角色">{{ roleStrategy[selectedUser?.role]?.name }}</el-descriptions-item>
                <el-descriptions-item label="创建时间">{{ selectedUser?.createTime }}</el-descriptions-item>
            </el-descriptions>

            <el-divider />

            <h4>权限列表</h4>
            <el-tag v-for="permission in roleStrategy[selectedUser?.role]?.permissions" :key="permission"
                style="margin-right: 8px; margin-bottom: 8px">
                {{ permission.split(':')[1] }} {{ permission.split(':')[0] }}
            </el-tag>
        </el-dialog>
    </div>
</template>

<style scoped>
    .page-container {
        padding: 20px;
    }

    .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
</style>